package com.sojson.util.security.shiro.securityManager;

import org.apache.shiro.authc.Authenticator;
import org.apache.shiro.authc.LogoutAware;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.mgt.WebSecurityManager;

import lombok.extern.slf4j.Slf4j;

/**
 * 自定义DefaultWebSecurityManager
 * 
 * @author liu
 * @date 2020-08-08
 */
@Slf4j
public class CustomSecurityManager extends DefaultWebSecurityManager implements WebSecurityManager {

    @Override
    public void logout(Subject subject) {

        if (subject == null) {
            throw new IllegalArgumentException("Subject method argument cannot be null.");
        }

        beforeLogout(subject);

        PrincipalCollection principals = subject.getPrincipals();
        if (principals != null && !principals.isEmpty()) {
            if (log.isDebugEnabled()) {
                log.info("Logging out subject with primary principal {}", principals.getPrimaryPrincipal());
            }
            Authenticator authc = getAuthenticator();
            if (authc instanceof LogoutAware) {
                ((LogoutAware)authc).onLogout(principals);
            }
        }

        // =======================================================================================================
        // // 新的 ,删除session的时候感觉没必要再去删除里面的属性,所以去掉了
        // try {
        // stopSession(subject);
        // } catch (Exception e) {
        // if (log.isDebugEnabled()) {
        // String msg = "Unable to cleanly stop Session for Subject [" + subject.getPrincipal() + "] "
        // + "Ignoring (logging out).";
        // log.info(msg, e);
        // }
        // }
        // TODO 原来的,这里可以优化！！！
        try {
            delete(subject);
        } catch (Exception e) {
            if (log.isDebugEnabled()) {
                String msg = "Unable to cleanly unbind Subject.  Ignoring (logging out).";
                log.info(msg, e);
            }
        } finally {
            try {
                stopSession(subject);
            } catch (Exception e) {
                if (log.isDebugEnabled()) {
                    String msg = "Unable to cleanly stop Session for Subject [" + subject.getPrincipal() + "] "
                        + "Ignoring (logging out).";
                    log.info(msg, e);
                }
            }
        }
        // =======================================================================================================
    }

}